package com.tjrac.zhaopin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.tjrac.zhaopin.bean.EditResumeReq;
import com.tjrac.zhaopin.bean.PostResumeReq;
import com.tjrac.zhaopin.entity.HunterInfo;
import com.tjrac.zhaopin.entity.JobList;
import com.tjrac.zhaopin.entity.PostInfo;
import com.tjrac.zhaopin.entity.SysUser;
import com.tjrac.zhaopin.mapper.PostInfoMapper;
import com.tjrac.zhaopin.service.HunterInfoService;
import com.tjrac.zhaopin.service.JobListService;
import com.tjrac.zhaopin.service.PostInfoService;
import com.tjrac.zhaopin.service.SysUserService;
import javafx.geometry.Pos;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/jobHunter")
public class HunterController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    HunterInfoService hunterInfoService;
    @Autowired
    JobListService jobListService;
    @Autowired
    PostInfoService postInfoService;
    @Autowired
    PostInfoMapper postInfoMapper;

    /**
     * 编辑简历
     * @param editResumeReq
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/editResume")
    public R editResume(@RequestBody EditResumeReq editResumeReq) {
        HunterInfo hunterInfo = new HunterInfo();
        BeanUtils.copyProperties(editResumeReq, hunterInfo);
        SysUser sysUser = sysUserService.getById(editResumeReq.getHunterId());
        sysUser.setEmail(editResumeReq.getEmail());
        sysUser.setMobile(editResumeReq.getMobile());
        sysUserService.saveOrUpdate(sysUser);
        HunterInfo hunterInfo1 = hunterInfoService.getOne(new QueryWrapper<HunterInfo>()
                .eq("hunter_id", editResumeReq.getHunterId()));
        if (hunterInfo1 != null) {
            hunterInfo.setId(hunterInfo1.getId());
            hunterInfoService.updateById(hunterInfo);
        } else {
            hunterInfoService.save(hunterInfo);
        }
        return R.ok("保存成功！");
    }

    /**
     * 浏览职位
     * @param id
     * @return
     */
    @GetMapping("/findJob")
    public R findJob(@RequestParam String id) {
        try {
            List<JobList> jobLists = jobListService.list();
            HunterInfo hunterInfo = hunterInfoService.getOne(new QueryWrapper<HunterInfo>().eq("hunter_id", id));
            CalcCorrelation calcCorrelation = new CalcCorrelation(hunterInfo);
            //对职位列表进行相关度计算后进行冒泡排序
            for (int i = 0; i < jobLists.size(); i++) {
                for (int j = 0; j < jobLists.size() - 1; j++) {
                    int score1 = calcCorrelation.calc(jobLists.get(i));
                    int score2 = calcCorrelation.calc(jobLists.get(j));
                    if (score1 > score2) {
                        JobList temp = jobLists.get(i);
                        jobLists.set(i, jobLists.get(j));
                        jobLists.set(j, temp);
                    }
                }
            }
            return R.ok(jobLists);
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("查询失败！");
        }
    }

    /**
     * 投递简历
     * @param postResumeReq
     * @return
     */
    @PostMapping("/postResume")
    @Transactional(rollbackFor = Exception.class)
    public R postResume(@RequestBody PostResumeReq postResumeReq) {
        PostInfo p = postInfoService.getOne(
                new QueryWrapper<PostInfo>()
                        .eq("hunter_id", postResumeReq.getHunterId())
                        .eq("job_id", postResumeReq.getId())
        );
        if (p != null) {
            return R.failed("您已经投递过该职位了！");
        }
        PostInfo postInfo = new PostInfo();
        postInfo.setHunterId(postResumeReq.getHunterId());
        postInfo.setJobId(postResumeReq.getId());
        postInfo.setPostStatus(1);
        postInfo.setStatus(0);
        postInfoService.save(postInfo);
        JobList jobList = jobListService.getById(postResumeReq.getId());
        if (jobList != null) {
            jobList.setPostedNum(jobList.getPostedNum() + 1);
            jobListService.updateById(jobList);
        }
        return R.ok("投递成功！");
    }

    /**
     * 投递情况
     */
    @GetMapping("/postResumeStatus")
    public R postResumeStatus(@RequestParam String id){
        return R.ok(postInfoMapper.listPostResumeStatus(new Integer(id)));
    }
}

class CalcCorrelation {
    private HunterInfo hunterInfo;

    CalcCorrelation(HunterInfo hunterInfo) {
        this.hunterInfo = hunterInfo;
    }

    /**
     * 职位推荐算法
     * 以权重计算为准：职位工作地点与意向工作地点符合的权重为7，职位TAG吻合度的权重为10，最低薪水吻合度（职位大于等于意向）的权重为3。
     * 例：有职位工作地点在天津，职位TAG为"前端开发工程师","全栈开发工程师","Vue开发工程师","PHP开发工程师"，最低薪水为6000元
     * 求职者的意向工作地点在天津，职位TAG为"前端开发工程师","Vue开发工程师",最低薪水为7000元
     * 则该职位的推荐分数为：7*1 + 10*(1+1) + 3*0
     *
     * @param jobList
     * @return
     */
    public int calc(JobList jobList) {
        int regionScore = 0;
        int tagScore = 0;
        int salaryScore = 0;
        if (jobList.getRegion().equals(hunterInfo.getRegion())) regionScore += 7;
        if (jobList.getSalaryMin() >= hunterInfo.getSalaryMin()) salaryScore += 3;
        List<String> hunterTag = JSON.parseArray(hunterInfo.getTag(), String.class);
        List<String> jobTag = JSON.parseArray(jobList.getTag(), String.class);
        //对两个TAG集合取交集
        hunterTag.retainAll(jobTag);
        tagScore += hunterTag.size() * 10;
        return regionScore + tagScore + salaryScore;
    }
}

